$(function () {
  // ----------------------------------- 退出登录 ------------------
  $(".logout").click(function (e) {
    e.preventDefault();
    localStorage.setItem("token", "");
    location.href = `${location.protocol}login.html`;
  });
  // ----------------------------------- 获取学员数据 ---------------
  axios.defaults.baseURL = "http://www.itcbc.com:8000";
  let token = localStorage.getItem("token");
  function getStudent() {
    axios({
      method: "GET",
      url: "/student/list",
      Headers: {
        Authorization: token,
      },
    }).then(({ data: res }) => {
      console.log(res);
      $("tbody").empty();
      studentIn(res.data);
    });
  }
  getStudent();

  // ----------------------------------- 删除学员 --------------------
  $("tbody").on("click", ".btn", function () {
    let id = $(this).attr("data-id");
    axios({
      method: "delete",
      url: "/student/delete",
      Headers: {
        Authorization: token,
      },
      params: {
        id: id,
      },
    }).then((res) => {
      console.log(res);
      getStudent();
    });
  });

  // ------------------------------------ 初始化数据 (一进入页面自动执行)-------------------------------
  // 此接口随机创建50名学员  ------ 不需要做任何处理
  axios.get("/init/data").then(({ data: res }) => {
    if (res.code === 0) {
      alert(res.message);
      getStudent();
    }
  });
});
//--------------------------------------------渲染封装
function studentIn(array) {
  $.each(array, function (index, item) {
    let studentId = $(`   <tr>
  <th scope="row">${item.id}</th>
  <td>${item.name}</td>
  <td>${item.age}</td>
  <td>${item.sex}</td>
  <td>${item.group}</td>
  <td>${item.phone}</td>
  <td>${item.salary}</td>
  <td>${item.truesalary}</td>
  <td>${item.province + item.city + item.county}</td>
  <td>
    <button type="button" class="btn btn-danger btn-sm" data-id=${item.id}>
      删除
    </button>
  </td>`);
    $("tbody").append(studentId);
  });
}
